
package com.ruoyi.gisconverter.core.type;

import org.geotools.data.DataUtilities;
import org.geotools.data.FeatureSource;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.wfs.GML;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;


public class GmlFile extends FileProcess {

    @Override
    public FeatureSource readFile(File file) {
        try {
            GML gml = null;
            SimpleFeatureCollection fc = null;
            try {
                InputStream in = file.toURI().toURL().openStream();
                gml = new GML(GML.Version.WFS1_0);
                fc = gml.decodeFeatureCollection(in);
                in.close();
            } catch (Exception e) {
                try {
                    InputStream in = file.toURI().toURL().openStream();
                    gml = new GML(GML.Version.WFS1_1);
                    fc = gml.decodeFeatureCollection(in);
                    in.close();
                } catch (Exception ex) {
                    throw ex;
                }
            }

            if (fc != null) {
                return DataUtilities.source(fc);
            }

        } catch (Exception e) {
            throw new RuntimeException("Error while reading GML File!!!", e);
        }

        return null;
    }

    @Override
    public void writeFile(FeatureSource fs, File file) {
        try {
            SimpleFeatureType schema = ff.fixNullCRSWithWGS84((SimpleFeatureType) fs.getSchema());
            OutputStream out = new FileOutputStream(file);
            GML gml = new GML(GML.Version.WFS1_0);
            gml.setNamespace("geotools", "http://geotools.org");
            gml.setCoordinateReferenceSystem(schema.getCoordinateReferenceSystem());
            
            gml.encode(out, (SimpleFeatureCollection) fs.getFeatures());
            out.close();
        } catch (Exception ex) {
            throw new RuntimeException("Error while writing GML File!!!", ex);
        }
    }

}
